package com.jbxie.spaceiotmqtt.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.ninwoo.bishe.starter.service.NetworkService;
import top.ninwoo.common.entity.DockerContainer;
import top.ninwoo.utils.util.DockerUtils;
import top.ninwoo.utils.util.LinuxCtlUtils;

import java.util.List;

@Service
class IPService {
    @Autowired
    private NetworkService networkService;

    @Autowired(required=false)
    private LinuxCtlUtils linuxCtlUtils;

    @Autowired(required=false)
    private DockerUtils dockerUtils;

    public String getDockerId() {
        String cmd = "head -1 /proc/self/cgroup|cut -d/ -f3|cut -c1-12";
        String res = linuxCtlUtils.runCmd(cmd);
        if(res == null) {
            throw new RuntimeException("get Docker Id Error");
        }
        return res;
    }

    public String getSelfDockerIpById(Long clusterId) {
        String id = getDockerId();
        DockerContainer dockerContainer = dockerUtils.getDockerById(id);
        return getIpByAppName(clusterId, dockerContainer.getName());
    }

    public String getIpByAppName(Long clusterId,String appName) {
        List<String> ipList = networkService.getIpListByAppName(clusterId, appName);
        if(!ipList.isEmpty()){
            String ip_tmp = ipList.get(0);
            String[] split_list = ip_tmp.split("/");
            return split_list[0] + ":8775";
        }
        return null;
    }

    public String[] getIpList(Long clusterId, String[] wxName_list) {
        int n = wxName_list.length;
        String[] ipList = new String[n];
        for (int k = 0; k < wxName_list.length; k++){
            ipList[k] = getIpByAppName(clusterId,wxName_list[k]);//通过卫星名字获取卫星ip
        }
        return ipList;
    }

}

